package zhibi.plugin.image.core;

import com.alibaba.fastjson.JSON;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 执笔 on 2016/12/30.
 * 图片处理器
 */
public class ImageHandler {

    private static final String DOWN = "down";
    private static final String VIEW = "view";
    private static final String INFO = "info";

    private HttpServletRequest request;
    private HttpServletResponse response;
    private String filePath;

    public void handler(final String target, final HttpServletRequest request, final HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.filePath = request.getServletContext().getRealPath(target);
        String type = request.getParameter("t");
        if (DOWN.equals(type)) {//下载图片
            downImg();
        } else if (INFO.equals(type)) {//图片信息
            infoImg();
        } else {//显示图片   默认
            viewImg();
        }
    }

    private void viewImg() {
        try {
            String path = getThumbPath();
            File file = new File(path);
            String fileName = file.getName();
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Length", file.length()+"");
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("image/" + path.substring(path.lastIndexOf(".")+1) + "; charset=utf-8");
            out.write(buffer);
            out.flush();
            out.close();
        } catch (IOException ex) {
        }
    }

    private HttpServletResponse infoImg() {
        try {
            File file = new File(filePath);
            Map<String, String> result = new HashMap<String, String>();
            if (!file.exists()) {
                result.put("msg", "文件不存在");
            } else {
                BufferedImage bufferedImage = ImageIO.read(file);
                result.put("name", file.getName());
                result.put("size", file.length() + "");
                result.put("width", bufferedImage.getWidth()+"");
                result.put("height", bufferedImage.getHeight() + "");
            }
            response.reset();
            OutputStream out = new BufferedOutputStream(
                    response.getOutputStream());
            String userAgent = request.getHeader("User-Agent");
            // 处理IE返回json跳出下载框
            if (userAgent.contains("MSIE")) {
                response.setContentType("text/html;charset=utf-8");
            } else {
                response.setContentType("application/json;charset=utf-8");
            }
            out.write(JSON.toJSONString(result).getBytes());
            out.flush();
            out.close();
        } catch (IOException ex) {
        }
        return response;
    }

    private void downImg(){
        try {
            String path = getThumbPath();
            File file = new File(path);
            String fileName = file.getName();
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            response.addHeader("Content-Length", "" + file.length());
            response.addHeader("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
            OutputStream out = new BufferedOutputStream(
                    response.getOutputStream());
            response.setContentType("application/octet-stream");
            out.write(buffer);
            out.flush();
            out.close();
        } catch (IOException ex) {
        }
    }

    /**
     * 得到 处理后 图片的路径
     *
     * @return
     */
    private String getThumbPath() {
        int width = 0, height = 0;
        double quality = 0.0D, scale = 0.0D, rotate = 0.0D;
        String thumbPath = filePath;
        if (null != request.getParameter("q")) {// 图片质量
            quality = paramDouble("q");
        }
        if (null != request.getParameter("r")) {// 旋转角度
            rotate = paramDouble("r");
        }
        if (null != request.getParameter("s")) {// 按比例  就忽略宽度和高度
            scale = paramDouble("s");
        } else {
            if (null != request.getParameter("w")) {// 宽度
                width = paramInt("w");
            }
            if (null != request.getParameter("h")) {// 高度
                height = paramInt("h");
            }
        }
        boolean isforce = true; // 是否保持图片比例
        if (width > 0 && height > 0) {
            isforce = false;
        }
        thumbPath = getImgPath(width, height, isforce, quality, scale, rotate);
        thumbPath = ThumbExec.thumb(filePath, thumbPath, width,
                height, isforce, scale, quality, rotate);
        return thumbPath;
    }

    private String getImgPath(int width, int height, boolean isforce, double quality, double scale, double rotate) {
        String suffix = filePath.substring(filePath.lastIndexOf(".") + 1);
        String path = filePath.substring(0, filePath.lastIndexOf("."));
        if (width > 0) path += "_w" + width;
        if (height > 0) path += "_h" + height;
        if (!isforce) path += "_false";
        if (quality > 0) path += "_q" + quality;
        if (scale > 0) path += "_s" + scale;
        if (rotate > 0) path += "_r" + rotate;
        return path + "." + suffix;
    }

    private double paramDouble(String paramName) {
        String value = request.getParameter(paramName);
        try {
            return Double.parseDouble(value);
        } catch (Exception e) {
            return 0D;
        }
    }

    private int paramInt(String paramName) {
        String value = request.getParameter(paramName);
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            return 0;
        }
    }
}
